# -*- coding: utf-8 -*-

"""
设置对话框
"""

from PyQt5.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QPushButton,
                             QLabel, QComboBox, QSlider, QCheckBox, QGroupBox,
                             QFormLayout, QDialogButtonBox, QButtonGroup, QRadioButton,
                             QFileDialog, QLineEdit, QScrollArea, QWidget, QFrame)
from PyQt5.QtCore import Qt


class SettingsDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("游戏设置")
        self.resize(400, 400)  # 使用resize替代setFixedSize以适应不同屏幕
        self.init_ui()
        self.load_settings()  # 添加: 加载已保存的设置
        
    def init_ui(self):
        """初始化界面"""
        # 创建主布局
        main_layout = QVBoxLayout(self)
        
        # 创建滚动区域以适应小屏幕
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setFrameShape(QFrame.NoFrame)
        
        # 创建内容部件
        content_widget = QWidget()
        content_layout = QVBoxLayout(content_widget)
        content_layout.setSpacing(15)
        
        # 游戏设置组
        game_group = QGroupBox("游戏设置")
        game_layout = QFormLayout()
        game_layout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)  # 确保控件可扩展
        
        # 难度选择
        self.difficulty_combo = QComboBox()
        self.difficulty_combo.addItems(["简单", "中等", "困难", "专家"])
        game_layout.addRow(QLabel("难度:"), self.difficulty_combo)
        
        # 拼图片数
        self.pieces_slider = QSlider(Qt.Horizontal)
        self.pieces_slider.setMinimum(3)
        self.pieces_slider.setMaximum(10)
        self.pieces_slider.setValue(4)
        self.pieces_slider.setMinimumSize(100, 20)  # 设置最小尺寸确保可见
        self.pieces_label = QLabel("4x4")
        pieces_layout = QHBoxLayout()
        pieces_layout.addWidget(self.pieces_slider)
        pieces_layout.addWidget(self.pieces_label)
        game_layout.addRow(QLabel("拼图片数:"), pieces_layout)
        
        # 连接滑块事件
        self.pieces_slider.valueChanged.connect(self.update_pieces_label)
        
        game_group.setLayout(game_layout)
        content_layout.addWidget(game_group)
        
        # 图片设置组
        image_group = QGroupBox("图片设置")
        image_layout = QFormLayout()
        image_layout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)
        
        # 图片目录选择
        self.image_dir_edit = QLineEdit()
        self.image_dir_edit.setPlaceholderText("请选择图片目录")
        image_dir_button = QPushButton("浏览...")
        image_dir_button.clicked.connect(self.select_image_directory)
        image_dir_layout = QHBoxLayout()
        image_dir_layout.addWidget(self.image_dir_edit)
        image_dir_layout.addWidget(image_dir_button)
        image_layout.addRow(QLabel("拼图图片目录:"), image_dir_layout)
        
        image_group.setLayout(image_layout)
        content_layout.addWidget(image_group)
        
        # 关闭行为设置组
        close_group = QGroupBox("关闭行为")
        close_layout = QVBoxLayout()
        close_layout.setSpacing(5)
        
        # 创建单选按钮组
        self.close_behavior_group = QButtonGroup(self)
        
        self.minimize_radio = QRadioButton("最小化到系统托盘")
        self.close_radio = QRadioButton("直接关闭软件")
        
        # 添加到按钮组
        self.close_behavior_group.addButton(self.minimize_radio, 1)
        self.close_behavior_group.addButton(self.close_radio, 2)
        
        close_layout.addWidget(self.minimize_radio)
        close_layout.addWidget(self.close_radio)
        
        close_group.setLayout(close_layout)
        content_layout.addWidget(close_group)
        
        # AI设置组
        ai_group = QGroupBox("AI设置")
        ai_layout = QVBoxLayout()
        ai_layout.setSpacing(5)
        
        self.emotion_ai_checkbox = QCheckBox("启用情感分析AI")
        self.emotion_ai_checkbox.setChecked(True)
        ai_layout.addWidget(self.emotion_ai_checkbox)
        
        self.difficulty_ai_checkbox = QCheckBox("启用难度自适应")
        self.difficulty_ai_checkbox.setChecked(True)
        ai_layout.addWidget(self.difficulty_ai_checkbox)
        
        ai_group.setLayout(ai_layout)
        content_layout.addWidget(ai_group)
        
        # 将内容部件添加到滚动区域
        scroll_area.setWidget(content_widget)
        main_layout.addWidget(scroll_area)
        
        # 确定和取消按钮
        button_box = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        main_layout.addWidget(button_box)
        
    def load_settings(self):
        """加载已保存的设置"""
        # 从游戏逻辑加载设置
        from src.game_logic import GameLogic
        game_logic = GameLogic()
        
        # 加载难度设置
        difficulty = game_logic.config.get("game.default_difficulty", "中等")
        index = self.difficulty_combo.findText(difficulty)
        if index >= 0:
            self.difficulty_combo.setCurrentIndex(index)
        
        # 加载拼图片数设置
        pieces = game_logic.config.get("game.default_puzzle_size", 4)
        self.pieces_slider.setValue(pieces)
        self.update_pieces_label(pieces)
        
        # 加载图片目录设置
        image_dir = game_logic.config.get("images.puzzle_image_directory", "")
        self.image_dir_edit.setText(image_dir)
        
    def accept(self):
        """接受设置更改"""
        # 保存设置
        from src.game_logic import GameLogic
        game_logic = GameLogic()
        
        # 保存难度设置
        game_logic.update_game_setting("default_difficulty", self.difficulty_combo.currentText())
        
        # 保存拼图片数设置
        game_logic.update_game_setting("default_puzzle_size", self.pieces_slider.value())
        
        # 保存图片目录设置
        image_dir = self.get_image_directory()
        if image_dir:
            game_logic.update_image_directory_setting(image_dir)
            
        super().accept()

    def update_pieces_label(self, value):
        """更新拼图片数标签"""
        self.pieces_label.setText(f"{value}x{value}")
        
    def select_image_directory(self):
        """选择图片目录"""
        directory = QFileDialog.getExistingDirectory(self, "选择图片目录")
        if directory:
            self.image_dir_edit.setText(directory)
        
    def set_close_behavior(self, behavior):
        """设置关闭行为选项"""
        if behavior == "minimize":
            self.minimize_radio.setChecked(True)
        elif behavior == "close":
            self.close_radio.setChecked(True)
        else:
            # 默认都不选中，让用户自己选择
            self.minimize_radio.setChecked(False)
            self.close_radio.setChecked(False)
            
    def get_close_behavior(self):
        """获取关闭行为设置"""
        if self.minimize_radio.isChecked():
            return "minimize"
        elif self.close_radio.isChecked():
            return "close"
        else:
            return None
            
    def set_image_directory(self, directory):
        """设置图片目录"""
        self.image_dir_edit.setText(directory)
        
    def get_image_directory(self):
        """获取图片目录"""
        return self.image_dir_edit.text()